package handlers

import (
	"github.com/nfnt/resize"
	"image"
	"image/color"
	"image/draw"
	"math"
)

type WriteImage struct {
	Path   string
	X      int
	Y      int
	Width  int
	Height int
	Circle bool
}

func (w *WriteImage) Process(img *image.RGBA) (*image.RGBA, error) {
	copyImg, err := LoadImage(w.Path)
	if err != nil {
		return img, err
	}
	if w.Width > 0 || w.Height > 0 {
		copyImg = resize.Resize(uint(w.Width), uint(w.Height), copyImg, resize.Lanczos3)
	}
	// 如果需要圆形
	if w.Circle {
		var (
			width, height, d int
		)
		width = copyImg.Bounds().Max.X - copyImg.Bounds().Min.X
		height = copyImg.Bounds().Max.Y - copyImg.Bounds().Min.Y
		d = width
		if width > height {
			d = height
		}

		// TODO 这里的外面的白圈不是透明的 暂时不知道怎么处理
		circleImg := NewCircleMask(copyImg, image.Pt(d/2, d/2), d)
		draw.Draw(img, img.Bounds().Add(image.Pt(w.X, w.Y)), circleImg, circleImg.Bounds().Min, draw.Src)
	} else {
		draw.Draw(img, img.Bounds().Add(image.Pt(w.X, w.Y)), copyImg, copyImg.Bounds().Min, draw.Src)
	}
	return img, nil
}

func NewCircleMask(img image.Image, p image.Point, d int) CircleMask {
	return CircleMask{img, p, d}
}

type CircleMask struct {
	image    image.Image
	point    image.Point
	diameter int
}

func (ci CircleMask) ColorModel() color.Model {
	return ci.image.ColorModel()
}

func (ci CircleMask) Bounds() image.Rectangle {
	return image.Rect(0, 0, ci.diameter, ci.diameter)
}

func (ci CircleMask) At(x, y int) color.Color {
	d := ci.diameter
	dis := math.Sqrt(math.Pow(float64(x-d/2), 2) + math.Pow(float64(y-d/2), 2))
	if dis > float64(d)/2 {
		return ci.image.ColorModel().Convert(color.RGBA{R: 255, G: 255, B: 255, A: 255})
	} else {
		return ci.image.At(x, y)
	}
}
